"""Flask 和 loguru 日志集成"""
import os
import sys
from typing import Dict, Any
from pathlib import Path
from loguru import logger
from flask import Flask, request, g
from datetime import datetime

from app.config import settings


def setup_logging(app: Flask) -> None:
    """设置 loguru 日志配置"""
    
    # 移除默认的处理器
    logger.remove()
    
    # 确保日志目录存在
    log_dir = Path(settings.log_file).parent
    log_dir.mkdir(parents=True, exist_ok=True)
    
    # 添加控制台输出处理器
    logger.add(
        sys.stdout,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
               "<level>{level: <8}</level> | "
               "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
               "<level>{message}</level>",
        level=settings.log_level,
        colorize=True
    )
    
    # 添加文件输出处理器
    logger.add(
        settings.log_file,
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} | {message}",
        level=settings.log_level,
        rotation="10 MB",
        retention="30 days",
        compression="zip",
        encoding="utf-8"
    )
    
    # 添加错误日志文件处理器
    error_log_file = str(Path(settings.log_file).parent / "error.log")
    logger.add(
        error_log_file,
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} | {message}",
        level="ERROR",
        rotation="10 MB",
        retention="30 days",
        compression="zip",
        encoding="utf-8"
    )
    
    # 禁用Flask默认日志
    app.logger.disabled = True
    
    # 设置werkzeug日志级别
    import logging
    logging.getLogger('werkzeug').setLevel(logging.WARNING)


def setup_request_logging(app: Flask) -> None:
    """设置请求日志记录"""
    
    @app.before_request
    def log_request_info():
        """记录请求信息"""
        g.start_time = datetime.now()
        
        # 记录请求基本信息
        logger.info(
            f"请求开始 - {request.method} {request.path} | "
            f"IP: {request.remote_addr} | "
            f"User-Agent: {request.headers.get('User-Agent', 'Unknown')}"
        )
        
        # 记录请求参数（敏感信息需要过滤）
        if request.method in ['POST', 'PUT', 'PATCH']:
            try:
                json_data = request.get_json() or {}
                filtered_data = filter_sensitive_data(json_data)
                if filtered_data:
                    logger.debug(f"请求体: {filtered_data}")
            except Exception:
                pass
        
        # 记录查询参数
        if request.args:
            filtered_args = filter_sensitive_data(dict(request.args))
            logger.debug(f"查询参数: {filtered_args}")
    
    @app.after_request
    def log_response_info(response):
        """记录响应信息"""
        duration = datetime.now() - g.start_time
        duration_ms = duration.total_seconds() * 1000
        
        logger.info(
            f"请求完成 - {request.method} {request.path} | "
            f"状态码: {response.status_code} | "
            f"耗时: {duration_ms:.2f}ms"
        )
        
        return response
    
    @app.teardown_request
    def log_request_teardown(error=None):
        """记录请求结束信息"""
        if error:
            logger.error(f"请求处理过程中发生错误: {str(error)}")


def filter_sensitive_data(data: Dict[str, Any]) -> Dict[str, Any]:
    """过滤敏感数据"""
    if not isinstance(data, dict):
        return data
    
    sensitive_keys = {
        'password', 'passwd', 'pwd', 'secret', 'token', 'key',
        'authorization', 'auth', 'credential', 'session'
    }
    
    filtered_data = {}
    for key, value in data.items():
        if any(sensitive_key in key.lower() for sensitive_key in sensitive_keys):
            filtered_data[key] = "***"
        elif isinstance(value, dict):
            filtered_data[key] = filter_sensitive_data(value)
        else:
            filtered_data[key] = value
    
    return filtered_data


# 导出logger实例供其他模块使用
__all__ = ['logger', 'setup_logging', 'setup_request_logging'] 